import React, { useState, useEffect } from 'react';
import { Shield, Play, Pause, Settings, Filter, Eye, EyeOff } from 'lucide-react';
import { GlobalCookieInterceptor } from '../utils/CookieInterceptor';
import { Tab } from '../../../contexts/AppContext';

interface CookieInterceptorPanelProps {
  tabs: Tab[];
  isOpen: boolean;
  onClose: () => void;
}

export function CookieInterceptorPanel({ tabs, isOpen, onClose }: CookieInterceptorPanelProps) {
  const [interceptorStatus, setInterceptorStatus] = useState<Record<string, any>>({});
  const [globalEnabled, setGlobalEnabled] = useState(true);
  const [autoInject, setAutoInject] = useState(true);
  const [autoExtract, setAutoExtract] = useState(true);
  const [showDetails, setShowDetails] = useState(false);

  const interceptorManager = GlobalCookieInterceptor.getInstance();

  // 更新拦截器状态
  const updateInterceptorStatus = () => {
    const status = interceptorManager.getAllStatus();
    setInterceptorStatus(status);
  };

  // 初始化拦截器
  useEffect(() => {
    if (isOpen) {
      // 为每个标签页创建拦截器
      tabs.forEach(tab => {
        if (!interceptorManager.getInterceptor(tab.id)) {
          interceptorManager.createInterceptor(tab.id, {
            enabled: globalEnabled,
            autoInject,
            autoExtract
          });
        }
      });

      if (globalEnabled) {
        interceptorManager.startAll();
      }

      updateInterceptorStatus();
      
      // 定期更新状态
      const interval = setInterval(updateInterceptorStatus, 2000);
      return () => clearInterval(interval);
    }
  }, [isOpen, tabs, globalEnabled, autoInject, autoExtract]);

  // 切换全局拦截状态
  const toggleGlobalEnabled = () => {
    const newEnabled = !globalEnabled;
    setGlobalEnabled(newEnabled);
    
    if (newEnabled) {
      interceptorManager.startAll();
    } else {
      interceptorManager.stopAll();
    }
    
    // 更新所有拦截器配置
    tabs.forEach(tab => {
      const interceptor = interceptorManager.getInterceptor(tab.id);
      if (interceptor) {
        interceptor.updateConfig({
          enabled: newEnabled,
          autoInject,
          autoExtract
        });
      }
    });
  };

  // 切换单个标签页的拦截状态
  const toggleTabInterceptor = (tabId: string) => {
    const interceptor = interceptorManager.getInterceptor(tabId);
    if (interceptor) {
      const currentStatus = interceptor.getStatus();
      if (currentStatus.isIntercepting) {
        interceptor.stop();
      } else {
        interceptor.start();
      }
      updateInterceptorStatus();
    }
  };

  // 获取标签页的账号信息
  const getTabAccountInfo = (tab: Tab) => {
    if (!tab.accountId) return '未绑定账号';
    return `${tab.platform} - ${tab.accountId.slice(0, 8)}...`;
  };

  // 计算统计信息
  const getStats = () => {
    const activeTabs = tabs.filter(tab => interceptorStatus[tab.id]?.isIntercepting);
    const totalCookies = Object.values(interceptorStatus).reduce((sum: number, status: any) => 
      sum + (status.cookieCount || 0), 0
    );
    
    return {
      activeTabs: activeTabs.length,
      totalTabs: tabs.length,
      totalCookies
    };
  };

  const stats = getStats();

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-4xl max-h-[80vh] overflow-hidden">
        {/* 标题栏 */}
        <div className="flex items-center justify-between p-4 border-b border-gray-200">
          <div className="flex items-center space-x-2">
            <Shield className="text-blue-500" size={24} />
            <h2 className="text-lg font-semibold text-gray-900">Cookie拦截器控制面板</h2>
          </div>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 text-lg"
          >
            ×
          </button>
        </div>

        {/* 控制面板内容 */}
        <div className="p-4 overflow-y-auto max-h-[calc(80vh-120px)]">
          {/* 全局控制 */}
          <div className="bg-gray-50 rounded-lg p-4 mb-4">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center space-x-2">
                <Settings size={20} className="text-gray-600" />
                <h3 className="text-md font-medium text-gray-900">全局设置</h3>
              </div>
              
              <button
                onClick={toggleGlobalEnabled}
                className={`flex items-center px-3 py-2 rounded ${
                  globalEnabled 
                    ? 'bg-green-500 text-white hover:bg-green-600' 
                    : 'bg-red-500 text-white hover:bg-red-600'
                }`}
              >
                {globalEnabled ? (
                  <><Pause size={16} className="mr-2" />暂停拦截</>
                ) : (
                  <><Play size={16} className="mr-2" />启动拦截</>
                )}
              </button>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="flex items-center space-x-2">
                <input
                  type="checkbox"
                  id="auto-inject"
                  checked={autoInject}
                  onChange={(e) => setAutoInject(e.target.checked)}
                  className="rounded"
                />
                <label htmlFor="auto-inject" className="text-sm text-gray-700">
                  自动注入Cookie
                </label>
              </div>
              
              <div className="flex items-center space-x-2">
                <input
                  type="checkbox"
                  id="auto-extract"
                  checked={autoExtract}
                  onChange={(e) => setAutoExtract(e.target.checked)}
                  className="rounded"
                />
                <label htmlFor="auto-extract" className="text-sm text-gray-700">
                  自动提取Cookie
                </label>
              </div>
              
              <div className="flex items-center space-x-2">
                <button
                  onClick={() => setShowDetails(!showDetails)}
                  className="flex items-center text-sm text-blue-600 hover:text-blue-800"
                >
                  {showDetails ? <EyeOff size={16} className="mr-1" /> : <Eye size={16} className="mr-1" />}
                  {showDetails ? '隐藏详情' : '显示详情'}
                </button>
              </div>
            </div>

            {/* 统计信息 */}
            <div className="mt-4 grid grid-cols-3 gap-4 text-center">
              <div className="bg-white rounded p-2 shadow-sm">
                <div className="text-2xl font-bold text-blue-600">{stats.activeTabs}</div>
                <div className="text-xs text-gray-600">活跃拦截</div>
              </div>
              <div className="bg-white rounded p-2 shadow-sm">
                <div className="text-2xl font-bold text-green-600">{stats.totalTabs}</div>
                <div className="text-xs text-gray-600">总标签页</div>
              </div>
              <div className="bg-white rounded p-2 shadow-sm">
                <div className="text-2xl font-bold text-purple-600">{stats.totalCookies}</div>
                <div className="text-xs text-gray-600">Cookie总数</div>
              </div>
            </div>
          </div>

          {/* 标签页列表 */}
          <div className="space-y-2">
            <h4 className="text-sm font-medium text-gray-900 mb-3">标签页控制</h4>
            
            {tabs.length === 0 ? (
              <div className="text-center py-8 text-gray-500">
                暂无标签页
              </div>
            ) : (
              tabs.map(tab => {
                const status = interceptorStatus[tab.id] || { isIntercepting: false, cookieCount: 0 };
                const isActive = status.isIntercepting;
                
                return (
                  <div
                    key={tab.id}
                    className={`flex items-center justify-between p-3 rounded border ${
                      isActive ? 'border-green-200 bg-green-50' : 'border-gray-200 bg-gray-50'
                    }`}
                  >
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center space-x-2 mb-1">
                        <span className={`w-2 h-2 rounded-full ${
                          isActive ? 'bg-green-500' : 'bg-gray-400'
                        }`}></span>
                        <span className="text-sm font-medium truncate">{tab.title}</span>
                        {tab.platform && (
                          <span className="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded">
                            {tab.platform}
                          </span>
                        )}
                      </div>
                      
                      <div className="text-xs text-gray-600 truncate">
                        {tab.url}
                      </div>
                      
                      {showDetails && (
                        <div className="mt-1 text-xs text-gray-500">
                          {getTabAccountInfo(tab)} • Cookie: {status.cookieCount || 0} 个
                        </div>
                      )}
                    </div>
                    
                    <div className="flex items-center space-x-2">
                      <span className={`text-xs px-2 py-1 rounded ${
                        isActive 
                          ? 'bg-green-100 text-green-800' 
                          : 'bg-gray-100 text-gray-800'
                      }`}>
                        {isActive ? '拦截中' : '已暂停'}
                      </span>
                      
                      <button
                        onClick={() => toggleTabInterceptor(tab.id)}
                        className={`p-1 rounded ${
                          isActive 
                            ? 'text-red-600 hover:bg-red-100' 
                            : 'text-green-600 hover:bg-green-100'
                        }`}
                        title={isActive ? '暂停拦截' : '启动拦截'}
                      >
                        {isActive ? <Pause size={16} /> : <Play size={16} />}
                      </button>
                    </div>
                  </div>
                );
              })
            )}
          </div>

          {/* 平台支持信息 */}
          <div className="mt-6 bg-yellow-50 border border-yellow-200 rounded-lg p-4">
            <div className="flex items-center space-x-2 mb-2">
              <Filter size={16} className="text-yellow-600" />
              <span className="text-sm font-medium text-yellow-800">支持的平台</span>
            </div>
            <div className="text-xs text-yellow-700">
              当前支持自动拦截的平台：抖音、快手、小红书、微博、B站等主流平台。
              拦截器会自动识别平台域名并应用相应的Cookie处理规则。
            </div>
          </div>
        </div>

        {/* 底部操作栏 */}
        <div className="border-t border-gray-200 px-4 py-3 bg-gray-50">
          <div className="flex justify-between items-center">
            <span className="text-xs text-gray-600">
              最后更新: {new Date().toLocaleTimeString()}
            </span>
            
            <div className="flex space-x-2">
              <button
                onClick={() => {
                  interceptorManager.stopAll();
                  onClose();
                }}
                className="px-4 py-2 text-sm text-gray-600 hover:text-gray-800"
              >
                关闭
              </button>
              
              <button
                onClick={() => {
                  if (globalEnabled) {
                    interceptorManager.startAll();
                  }
                  onClose();
                }}
                className="px-4 py-2 bg-blue-500 text-white text-sm rounded hover:bg-blue-600"
              >
                应用并关闭
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}